"""
门卫管理服务
创建时间：2025-09-12
作者：开发团队
目的：处理门卫管理相关业务逻辑
"""

from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from ..models.user import User
from ..models.verification import VerificationRecord
from ..schemas.admin import GuardCreate, GuardUpdate
from ..core.security import get_password_hash
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)


def get_guards(db: Session, skip: int = 0, limit: int = 100) -> list[User]:
    """
    获取门卫列表
    :param db: 数据库会话
    :param skip: 跳过的记录数
    :param limit: 返回的记录数
    :return: 门卫列表
    """
    try:
        return db.query(User).filter(User.role == "guard").offset(skip).limit(limit).all()
    except SQLAlchemyError as e:
        logger.error(f"查询门卫列表失败: {str(e)}")
        raise ValueError("查询门卫列表失败")


def get_guard_count(db: Session) -> int:
    """
    获取门卫总数
    :param db: 数据库会话
    :return: 门卫总数
    """
    try:
        return db.query(User).filter(User.role == "guard").count()
    except SQLAlchemyError as e:
        logger.error(f"查询门卫总数失败: {str(e)}")
        raise ValueError("查询门卫总数失败")


def get_guard_by_id(db: Session, guard_id: int) -> User | None:
    """
    根据ID获取门卫
    :param db: 数据库会话
    :param guard_id: 门卫ID
    :return: 门卫对象或None
    """
    try:
        return db.query(User).filter(User.id == guard_id, User.role == "guard").first()
    except SQLAlchemyError as e:
        logger.error(f"查询门卫失败: {str(e)}")
        return None


def get_guard_by_username(db: Session, username: str) -> User | None:
    """
    根据用户名获取门卫
    :param db: 数据库会话
    :param username: 用户名
    :return: 门卫对象或None
    """
    try:
        return db.query(User).filter(User.username == username, User.role == "guard").first()
    except SQLAlchemyError as e:
        logger.error(f"查询门卫失败: {str(e)}")
        return None


def create_guard(db: Session, guard_data: GuardCreate) -> User:
    """
    创建门卫账号
    :param db: 数据库会话
    :param guard_data: 门卫创建数据
    :return: 创建的门卫对象
    """
    try:
        # 检查用户名是否已存在
        existing_guard = get_guard_by_username(db, guard_data.username)
        if existing_guard:
            raise ValueError("该用户名的门卫已存在")
        
        # 创建门卫对象
        guard = User(
            username=guard_data.username,
            password_hash=get_password_hash(guard_data.password),
            name=guard_data.name,
            role="guard",
            phone=guard_data.phone,
            campus_id=guard_data.campus_id,
            status=guard_data.status
        )
        
        # 保存到数据库
        db.add(guard)
        db.commit()
        db.refresh(guard)
        
        logger.info(f"门卫账号创建成功: ID={guard.id}, 用户名={guard.username}")
        return guard
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"创建门卫账号失败: {str(e)}")
        raise ValueError("创建门卫账号失败")


def update_guard(db: Session, guard_id: int, guard_data: GuardUpdate) -> User | None:
    """
    更新门卫信息
    :param db: 数据库会话
    :param guard_id: 门卫ID
    :param guard_data: 门卫更新数据
    :return: 更新后的门卫对象或None
    """
    try:
        guard = db.query(User).filter(User.id == guard_id, User.role == "guard").first()
        if not guard:
            return None
        
        # 更新字段
        update_data = guard_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(guard, field, value)
        
        db.commit()
        db.refresh(guard)
        
        logger.info(f"门卫信息更新成功: ID={guard.id}, 用户名={guard.username}")
        return guard
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"更新门卫信息失败: {str(e)}")
        raise ValueError("更新门卫信息失败")


def delete_guard(db: Session, guard_id: int) -> bool:
    """
    删除门卫账号
    :param db: 数据库会话
    :param guard_id: 门卫ID
    :return: 是否删除成功
    """
    try:
        guard = db.query(User).filter(User.id == guard_id, User.role == "guard").first()
        if not guard:
            return False
        
        # 先删除与该门卫关联的所有核验记录
        db.query(VerificationRecord).filter(VerificationRecord.guard_id == guard_id).delete()
        
        # 然后删除门卫账号
        db.delete(guard)
        db.commit()
        
        logger.info(f"门卫账号删除成功: ID={guard_id}")
        return True
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"删除门卫账号失败: {str(e)}")
        raise ValueError("删除门卫账号失败")


def change_guard_password(db: Session, guard_id: int, new_password: str) -> bool:
    """
    修改门卫密码
    :param db: 数据库会话
    :param guard_id: 门卫ID
    :param new_password: 新密码
    :return: 是否修改成功
    """
    try:
        guard = db.query(User).filter(User.id == guard_id, User.role == "guard").first()
        if not guard:
            return False
        
        setattr(guard, 'password_hash', get_password_hash(new_password))
        db.commit()
        
        logger.info(f"门卫密码修改成功: ID={guard_id}, 用户名={guard.username}")
        return True
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"修改门卫密码失败: {str(e)}")
        raise ValueError("修改门卫密码失败")